package cn.jbit.user.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.github.pagehelper.Page;

import cn.jbit.pojo.Role;
import cn.jbit.pojo.User;
import cn.jbit.user.service.PermissionsService;
import cn.jbit.user.service.RoleService;
import cn.jbit.user.service.UserService;
import sun.net.www.content.text.plain;
/**
 * 控制层（用户）
 * @author Administrator
 */
@Controller
public class UserController {

	@Autowired
	private UserService userService;

	@Autowired
	private RoleService roleService;

	@Autowired
	private PermissionsService permissionsService;
	
	//登录页面
	@RequestMapping({"/login","/"})
	public String Login(HttpSession session) {
		
		return "login";
	}
	//进入主页面
	@RequestMapping("/indexs")
	public String iString() {
		
		return "index";
	}
	//进入用户修改页面 edituser.html
	@RequestMapping("/user_update")
	public String update_user(Model model,String userid,String user_name) {
		//查询供应商信息 
		List<Role> roleList = roleService.findRoleAll();
		//角色列表
		model.addAttribute("roleList",roleList);
		//用户id
		model.addAttribute("userid",userid);
		//用户名
		model.addAttribute("user_name",user_name);
		return "edituser";
	}
	//进入修改密码
	@RequestMapping("/user_update_pwd")
	public String user_pwd() {
		return "updatePwd";
	}
	//保存新密码以及比较旧密码
	@RequestMapping("/user_update_pwd_save")
	public String user_pwd_save(HttpServletRequest request,HttpSession session) {
		String pwd = request.getParameter("new_pwd_one");
		System.out.println("pwd=================>"+pwd);
		//取到当前对象
		User user = (User)session.getAttribute("user");
		user.setUser_password(pwd);
		int index = 0;
		try {
			index = userService.updateInfoId(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		if (index==1) {
			//修改成功
			request.setAttribute("pwd_result", "true");
			return "img";
		}
		request.setAttribute("pwd_result", "false");
		return "img";
	}
	//修改保存
	@RequestMapping("/user_update_save")
	@ResponseBody
	public Map<String, Object> update_user_save(Integer userid,Integer per_stat) {
		Map<String, Object> map = new HashMap<>();
		int perindex=0;//标记是否成功
		try {
			perindex = permissionsService.updatePerInfo(userid,
					per_stat);
		} catch (Exception e) {
			System.out.println("========================?per chucuo");
			e.printStackTrace();
		}
		if (perindex==1) {
			//成功
			map.put("data", "success");
		}else {
			map.put("data", "errors");
		}
		return map;
	}
	
	//分页查询数据 根据用户名字模糊查询
	@RequestMapping("/user_page_list")
	public String name(Integer pageNum,Model model,HttpServletRequest request) {
		//模糊查询的用户名 userphone
		String userphone = request.getParameter("userphone");
		String username = request.getParameter("username");
		//模糊查询权限id role_id
		Integer role_id = 0;
		if (request.getParameter("role_id")!=null&&request.getParameter("role_id")!="") {
			role_id =Integer.parseInt(request.getParameter("role_id"));
		}
		//查询供应商信息
		List<Role> roleList = roleService.findRoleAll();
		// 设置分页插件的参数
		if (pageNum==null) {
			pageNum=1;
		}
		Page<User> page = userService.findUserPage(pageNum,userphone,role_id,username);
		//分页信息
		model.addAttribute("userpage",page);
		model.addAttribute("role_id",role_id);
		model.addAttribute("userphone",userphone);
		//角色信息
		model.addAttribute("roleList",roleList);
		return "user";
	}
	//登录验证
	@RequestMapping("/user_login")
	@ResponseBody
	public Map<String, Object> userLogin(String userphone,String userpassword,HttpSession session,HttpServletRequest request) {
		String index = "true";//用来记录 运行异常还是运行正常
		Map<String, Object> map = new HashMap<>();
		User user = new User();
		user.setUser_phone(userphone);
		user.setUser_password(userpassword);
		//非空验证
		if (!user.getUser_phone().equals("")||!user.getUser_password().equals("")) {
			// 获取Subject主体对象
			Subject loginuser = SecurityUtils.getSubject();
			if (!loginuser.isAuthenticated()) {
				//如果没有认证便进入 创建令牌 将帐号密码存入令牌中1
				UsernamePasswordToken token = new UsernamePasswordToken
						(user.getUser_phone(),user.getUser_password());
				try {
					//去Realem
					loginuser.login(token);
				}catch (IncorrectCredentialsException e) {
					request.setAttribute("loginerror", "对不起您没有该权限！");
					index= "pwdfalse";
				}catch (UnknownAccountException e) {
					request.setAttribute("loginerror", "对不起您没有该权限！");
					index= "error";
				}
				catch (Exception e) {
					e.printStackTrace();
					index= "false";
				}
			}
		}else {
			index= "false";
		}
		if (index.equals("true")) {
			//如果有认证便进入 将当前对象存入session中
			User user2 = userService.findUserName(user.getUser_phone());
			System.out.println("user_role_rolename======================>"+user2.getRole().getRole_name());
			session.setAttribute("user", user2);
			map.put("data", "success");
			
		}else if(index.equals("false")){
			map.put("data", "false");
		}else if (index.equals("error")) {
			map.put("data", "error");
		}else if (index.equals("pwdfalse")) {
			map.put("data", "pwdfalse");
		}
		return map;
	}
	//进入注册页面
	@RequestMapping("/user_register")
	public String userRegister() {
		return "reg";
	}
	
	//注册信息保存
	@RequestMapping("/user_reg_saves")
	@ResponseBody
	public  String registerSave(String userphone,String userpassword) {
		System.out.println("进入reg_save方法==============================");
		User user = new User();
		user.setUser_phone(userphone);
		user.setUser_password(userpassword);
		String result = "";
		try {
			result= userService.userRegister(user);
		} catch (Exception e) {
			e.printStackTrace();
		}
		System.out.println("result===================>"+result);
		if (result.equals("register")) {
			//成功
			return "success";
		}else {
			//失败
			return "error";
		}
		
	}
	//查询数据库中是否有相同名字
	@RequestMapping("/user_name_sel")
	@ResponseBody
	public String userselname(String name) {
		Integer index = userService.findNameUser(name);
		if (index==1) {
			//如果查询到了数据
			return "false";
		}else {
			
			return "true";
		}
	}
	//新增微信程序中未在数据库中注册的用户
	@RequestMapping("/user_name_add")
	@ResponseBody
	public String user_add_name(String name,String password) {
		System.out.println("name=======>"+name+"password==========>"+password);
		Integer index = userService.addNameUser(name, password);
		if (index==1) {
			//查询当前用户的userid
			Integer userid = userService.findNameUser(name);
			System.out.println("userid================>"+userid);
			//给普通用户权限
			Integer perIndex = permissionsService.addUserRole(userid);
			if (perIndex==1) {
				return "true";
			}else {
				return "error";
			}                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                   
		}else {
			return "false";
		}
		
	}
	
	
	//查询注册号码是否被注册
	@RequestMapping("/reg_phone_repeat")
	@ResponseBody
	public Map<String, Object> reg_findPhoneRepeat(String userphone) {
		Map<String, Object> map = new HashMap<>();
		int index = userService.findUserPhone(userphone);
		if (index==0) {
			//没有找到
			map.put("data", "true");
		}else {
			map.put("data", "false");
		}
		return map;
	}
	//注销
	@RequestMapping("/user_loginout")
	public String loginOut() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "login";
	}
	//錯誤頁面
	@RequestMapping("/user_404")
	public String error() {
		return "404";
	}
	//进入图片页面
	@RequestMapping("/img")
	public String img() {
		Subject subject = SecurityUtils.getSubject();
		subject.logout();
		return "img";
	}
}
